import React, { Children, ReactElement, ReactNode, useContext } from "react";
import { NodeViewContext } from "../NodeViewContext";
import type Port from "./Port";
import { PortDirection } from "./Port";
import { NODE_ELEM_HEIGHT, NODE_ELEM_MARGIN } from "../NodeViewConfig";

interface Prop {
    children: ReactNode;
}

export function PortGroupView(prop: Prop) {
    let ctx = useContext(NodeViewContext);

    let children = prop.children;

    let portIn: ReactElement[] = [];
    let portOut: ReactElement[] = [];

    Children.forEach(prop.children, (child, index) => {
        if (child == null || typeof child != 'object' || (child as any).type.name != 'PortView') {
            throw new TypeError('invaild child element of PortView, got: ' + child);
        }

        let data = (child as ReactElement).props.data as Port;

        if (data.portDir == PortDirection.IN) {
            portIn.push(child as ReactElement);
        } else if (data.portDir == PortDirection.OUT) {
            portOut.push(child as ReactElement)
        }
    })

    console.log(ctx.width)

    return (
        <>
            {portIn.map((child, index) => {
                return (<NodeViewContext.Provider value={{
                    relX: ctx.relX,
                    relY: ctx.relY + (NODE_ELEM_HEIGHT + NODE_ELEM_MARGIN) * index,
                    height: ctx.height,
                    width: ctx.width
                }} key={index}>
                    {child}
                </NodeViewContext.Provider>)
            })}

            {portOut.map((child, index) => {
                return (<NodeViewContext.Provider value={{
                    relX: ctx.relX,
                    relY: ctx.relY + (NODE_ELEM_HEIGHT + NODE_ELEM_MARGIN) * index,
                    height: ctx.height,
                    width: ctx.width
                }} key={index}>
                    {child}
                </NodeViewContext.Provider>)
            })}
        </>
    )
}
